package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.activity.toJSONString
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.ParamsDTO
import com.abc.robot01.retrofit.bean.RenderPaymentRequest
import com.abc.robot01.retrofit.bean.RenderPaymentRequest2
import com.abc.robot01.retrofit.bean.RequestData
import com.abc.robot01.retrofit.bean.UserOrderDetailDTO
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class ZhifuViewModel : ViewModel() {
    val TAG = "ZhifuViewModel"

    val show =
        mutableStateOf(true)

    //    余额不足
//    val fail =
//        mutableStateOf(false)

    val userName = mutableStateOf("")
    val customerPhone = mutableStateOf("")
    val designPackageId = mutableStateOf("")
    val housePlansId = mutableStateOf("")
    val housePlanDataId = mutableStateOf("")
    val fee = mutableStateOf("0.0")
    val name = mutableStateOf("")
    val renderRoomIds = mutableListOf<String>()
    val skyBoxId = mutableStateOf("")

    val paySuccess = mutableStateOf(false)

    var base64 by mutableStateOf(
        "iVBORw0KGgoAAAANSUhEUgAAASkAAAEpCAYAAADPmdSCAAAD40lEQVR4nO3UMQEAIAzAMMC/5+GAlx6Jgl7dM7MAqs7vAIAXkwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIO0CI1AFT7xPGE4AAAAASUVORK5CYII=\n"
    )

    init {
        //发起异步任务
        viewModelScope.launch {
            val r = asyncTaskAsyncTask()
            if (r.not()) return@launch

            //生成小程序码
            base64 = genMiniProgramQrCode()

//                开始轮循,只有成功才返回
            val userId = poll()

            if(userId=="-1"){
                Log.e(TAG, "支付失败")
                show.value = false
                paySuccess.value = false
                return@launch
            }


            //授权成功,保存户型数据(渲染支付前调用)
            val s = RetrofitService.instance.housePlanData(
                userId=Robot.userId,
                accessToken = Robot.accessToken,
                request = RenderPaymentRequest2(
                    id = housePlanDataId.value,
                    housePlanId = housePlansId.value,
                    name = "",
                    skyBoxId = skyBoxId.value.also {
                        Log.e(TAG, "保存户型数据 天空盒 ID:" + it)
                    }
                ).also {
                    Log.e(TAG, "保存户型数据1028 参数:" + it)
                }
            )

            Log.e(TAG, "保存户型数据:" + s)
//            val a1 = JSONObject(s);
            if (s.code == 200 && s.message == "success") {
                Log.e(TAG, "保存户型数据成功:" + s)
            }

            // 开始支付
            val totalAmount = fee.value.toDouble()

            Log.e(TAG, "渲染支付  :companyId:" + Robot.companyId)
            val res = RetrofitService.instance.renderPay(
                Robot.accessToken, companyId = Robot.companyId,
                userId = userId,
                request = RenderPaymentRequest(userId = userId,
                    companyId = Robot.companyId,
                    totalAmount = totalAmount,
                    robotId = Robot.robotId,
                    customerName = userName.value,
                    renderName = name.value,
                    customerPhone = customerPhone.value,
                    userOrderDetailDTOList = listOf(
                        UserOrderDetailDTO(
                            productType = 7,
                            productUserId = Robot.userId,
                            productCompanyId = Robot.companyId,
                            productId = designPackageId.value,
                            detail = Detail(
                                renderRoomIds = renderRoomIds,
                                housePlansId = housePlansId.value,
                                housePlanDataId = housePlanDataId.value
                            ).toJSONString().also {
                                Log.e(TAG, "Detail:" + it)
                            },
                            productAmount = totalAmount
                        )
                    ).also {
                        Log.e(TAG, "渲染支付  :request:" + it)
                    }
                )
            )
            Log.e(TAG, "支付结果:" + res)
            if (res.code==200 && res.message == "success") {
                paySuccess.value = true
                show.value = false
            } else if (res.code == 400) {
                Log.e(TAG, "余额不足")
                paySuccess.value = false
//                fail.value = true
                show.value = false
            }
        }
    }

    data class Detail(
        val housePlansId: String,
        val housePlanDataId: String,
        val renderRoomIds: List<String>
    )
}

fun generateRandomId(length: Int = 8): String {
    val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    return (1..length)
        .map { allowedChars.random() }
        .joinToString("")
}

/**
 *  发起异步任务
 */
suspend fun asyncTaskAsyncTask(type: Int = 3): Boolean {
    Robot.randomId = generateRandomId()
    Log.e("asyncTaskAsyncTask", "发起异步任务 rid:" + Robot.randomId)
    val res = RetrofitService.instance.asyncTask(
        RequestData(
            sn = Robot.sn,
            type = type,
            rid = Robot.randomId,
            paramsDTO = ParamsDTO()
        )
    )

    val code =res.code
    if (code != 200) {
        Log.e("asyncTaskAsyncTask", "发起异步任务失败")
        return false
    }
    Log.e("asyncTaskAsyncTask", "发起异步任务成功:"+res)
    return true
}

/**
 * 轮循
 */
suspend fun poll(): String {
    while (true) {
        delay(2000)
        val a = RetrofitService.instance.pullAsyncTask(
            type = "3",
            sn = Robot.sn,
            rid = Robot.randomId,
            accessToken = Robot.accessToken
        )

        Log.e("PULL", "轮循支付结果:" + a)
        Log.e("PULL", "轮循支付结果:" + a.data.status)
        if (a.data.status == "PROCESS") {
            Log.e("PULL", "还在处理:")
        }
        else if (a.data.status == "FAILURE") {
            Log.e("PULL", "支付失败:")
            return  "-1"
        }
        else {
            Log.e("PULL", "授权成功")
            Log.e("PULL", " a.data.resultDTO.userId: " + a.data.resultDTO.userId)
            return a.data.resultDTO.userId;
        }
    }
}

/**
 *   员工管理 使用2
 *   申请管理使用 2
 */
suspend fun genMiniProgramQrCode(type:String="3"): String {
    val TAG = "生成小程序码"
    val res2 = RetrofitService.instance.genMiniProgramQrCode(
        accessToken = Robot.accessToken.also {
            Log.e(TAG, "accessToken:" + it)
            Log.e(TAG, "sn:" + Robot.sn)
            Log.e(TAG, "randomId:" + Robot.randomId)
        },
        type = type,
        sn = Robot.sn,
        rid = Robot.randomId,
    )
    val data = res2.data
    Log.e(TAG, "生成小程序码:" + res2)
    Log.e(TAG, "生成小程序码:" + data)
    return data
}
